<template>
	<view class="user-setting">
		<view class="item avatar" @click="handleAvatarTap">
			<image class="image" :src="avatar" mode="aspectFill" />
			<view class="action">
				<text>更换头像</text>

			</view>
		</view>
		<view class="containerItem">
			<text>昵称</text>
			<view class="rightContainer">
				<input v-if="!show" placeholder="编辑用户名" type="text" :value="form.name" @input="handleNameConfirm" />
			</view>
		</view>
		<view class="containerItem">
			<text>性别</text>
			<view @click="changeSex" class="changeBox">
				{{form.sex===0?'保密':form.sex===1?'男':'女'}}
			</view>
		</view>
		<view class="containerItem">
			<text>常住地</text>
			<view class="cityBox">
				<picker mode="region" :model="true" @change="bindRegionChange" :value="region">
					<text class="picker">
						{{region[0] ? region[0] : ''}} {{region[1] ? region[1] : ''}} {{region[2] ? region[2] : ''}}
						<!-- {{region.[0]}} -->
					</text>
				</picker>
			</view>
		</view>
		<!-- <view class="item log" >
	    <text>标签</text>
	    <view bind:tap="logs" class="logs rightBox" >
	      <view class="list" wx:if="{{userTags.length>0}}">
	        <view class="logitem" wx:for="{{userTags}}" wx:key="id">{{item.name}}</view>
	      </view>
	      <view class="list" wx:else>
	        <view class="logitem">+添加标签</view>
	      </view>
	      <image mode="aspectFill" src="/images/ic_arrow_smallgrey.png" />
	    </view>
	  </view> -->
		<view class="containerItem">
			<text>生日</text>
			<view class="birBox">
				<picker mode="date" :value="form.birth" start="1900-01-01" end="2020-06-01" @change="datePickerBindchange">
					{{form.birth?form.birth:'请选择'}}
				</picker>
				<view class="item">
				</view>
			</view>
		</view>
		<view class="containerItem ios">
			<text>介绍自己</text>
			<view class="bio">
				<textarea v-if="!show" :hold-keyboard="true" cursor-spacing="30" @input="handleBioConfirm" maxlength="50"
				 :auto-height="true" :value="form.bio"></textarea>
				<view class="tip" v-if="!form.bio">简单说说</view>
			</view>
		</view>
		<!-- <view class="containerItem {{systemInfo == 'ios' ? 'ios' : ''}} magTop20">
	    <text>收货地址</text>
	    <view class="bio imgPos" bind:tap="chooseAddress"><image mode="aspectFill" src="/images/ic_arrow_smallgrey.png" /></view>
	  </view> -->
		<view class="submit">
			<button @click="doSubmit" :loading="submitting" :disabled="submitting || !canSubmit">完成</button>
		</view>
	</view>
	<!-- <popup-login closable="{{closeable}}"></popup-login> -->

</template>

<script>
	import {
		$storage
	} from '@/utils'
	import uploadFile from "../common/uploadFile.js";
	const mimeTypeMap = {
		jpeg: 'image/jpeg',
		jpg: 'image/jpeg',
		png: 'image/png',
		gif: 'image/gif',
		mp4: 'video/mp4',
	}
	export default {
		data() {
			return {
				isMessage: false,
				user: {},
				form: {
					name: '',
					sex: 0,
					bio: '',
					location: '',
					birth: '',
				},
				canSubmit: false,
				region: ['未选择', '未选择', '未选择'],
				sexRange: ['保密', '男', '女'],
				submitting: false,
				avatar: '',
				systemInfo: '',
				show: false,
				hasbio: false,
				cropper: '',
				dateValue: '请选择',
			};
		},
		onShow() {
			this.getUserInfo()
		},
		async onLoad() {

		},
		created: function() {

		},
		methods: {
			async uploadAtv(path, size) {
				let res = await uploadFile(
					path,
					size,
					'https://sns.royole.fun/api/v2/storage'
				);
				return res
			},
			/* 上传头像 */
			postUserAtv(filePath) {
				console.log(filePath)
				return new Promise((resolve, reject) => {
					wx.uploadFile({
						url: 'https://fileserver.royole.fun/a1/multiupload?type=AVATAR',
						// url: 'https://fileserver.beta.royole.fun/a1/multiupload?type=AVATAR',//测试地址
						filePath,
						header: {
							"Content-Type":'multipart/form-data',
							"X-Auth-Token": $storage.get("passportToken"),
							"Paasport-Device-Id": $storage.get("rouyu-device-id"),
							"Paasport-App-Id": $storage.get("rouyu-app-id"),
							"X-Auth-UID": $storage.get("rouyu-user-id"),
						},
						name: 'file',
						formData: {
							type: 0,
						},
						success(res) {
							if (res.statusCode === 401) {
								uni.$emit('login')
								uni.showToast({
									title: '上传失败'
								})
								uni.hideLoading()
								return reject('请先登录')
							} else if (res.statusCode !== 200) {
								uni.showToast({
									title: '上传失败'
								})
								uni.hideLoading()
								return reject('失败')
							}
							return resolve(JSON.parse(res.data))
						},
						fail: (e) => {
							return reject('失败')
						},
					})
				})
			},
			/** 点击头像预览头像大图 */
			handlePreview(url) {
				console.log("read bg picd")
				uni.previewImage({
					urls: [url]
				});
			},
			handleAvatarTap() {
				uni.showModal({
					title: '确认上传头像吗?',
					content: '确认会直接更换现在已有的头像信息',
					confirmText: '确认',
					cancelText: '不上传',
					success: async ({
						confirm
					}) => {
						if (confirm) {
							uni.chooseImage({
								count: 1, //默认9
								sizeType: ["compressed"], //可以指定是原图还是压缩图，默认二者都有
								sourceType: ["album", "camera"], //从相册选择
								success: async ({
									tempFilePaths: {
										[0]: path
									}
								}) => {
									uni.showLoading({
										title: '上传中...'
									})
									const res = await this.postUserAtv(path)
									// const res = await this.uploadAtv(path,size)
									// await this.$u.api.saveUserInfo({ avatar: res.data.uri ,_method: "patch"})
									await this.$u.api.saveUserInfo({
										avatar: res.data[0],
										_method: "patch"
									})
									this.avatar = res.data[0]
									this.updateUserInfo()
									uni.showToast({
										title: '头像更新成功'
									})
									uni.hideLoading()
								}
							})
						}
					},
				})

			},

			getUserInfo() {
				const user = $storage.get('user') || {}
				this.user = user;
				this.form.name = user.name
				this.form.sex = user.sex
				this.form.bio = user.bio
				this.form.location = user.location
				this.form.birth = user.birth
				this.dateValue = user.birth
				this.canSubmit = false
				this.region = user.location ? user.location.split(' ') : ['未选择', '未选择', '未选择']
				this.avatar = typeof user.avatar === 'string' ? user.avatar : user.avatar.url
			},
			async updateUserInfo(update) {

				let user = await this.$u.api.getCurrentUser()
				$storage.set("user", user)
				uni.$emit("userInfoChange")
				let avatar = user.avatar
				user = { ...user,
					...update
				}
				if (!!update && ('avatar' in update) && avatar) {
					user.avatar = { ...avatar,
						...update.avatar
					}
				}
				$storage.set('user', user)
				this.user = user;
			},
			handleNameConfirm({
				detail: {
					value
				}
			}) {
				this.form.name = value;
				this.canSub()
			},
			handleBioConfirm({
				detail: {
					value
				}
			}) {
				this.$set(this.form, 'bio', value);
				if (value) {
					this.hasbio = true
				} else {
					this.hasbio = false
				}

				// this.form = Object.assign(this.form,{bio:value})
				this.canSub()
			},
			changeSex() {
				let _this = this;
				wx.showActionSheet({
					itemList: ['保密', '男', '女'],
					success: ({
						tapIndex
					}) => {
						_this.canSubmit = tapIndex !== _this.user.sex
						_this.form.sex = tapIndex
					},
				})
			},
			/**
			 * 生日选择
			 */
			datePickerBindchange(e) {
				this.dateValue = e.detail.value
				this.form.birth = e.detail.value
				// this.$set(this.form, 'birth', e.detail.value)
				// this.form.birth = e.detail.value
				console.log(this.form.birth)
				this.canSub()
			},
			/**
			 * 地区选择
			 */
			bindRegionChange: function(e) {
				const region = e.detail.value.filter((i) => i !== '未选择')
				if (region.length < 2) {
					wx.showModal({
						title: '提示',
						content: '请至少选择省市',
						showCancel: false,
					})
					return
				}
				this.form.location = region.join(' ');
				this.region = region;
				this.canSub()
			},
			canSub() {
				const user = this.user;
				const form = this.form;
				this.canSubmit = user.bio !== form.bio ||
					user.name !== form.name ||
					user.location !== form.location ||
					user.sex !== form.sex ||
					user.birth !== form.birth
			},
			async doSubmit() {
				const form = this.form;
				const submitting = this.submitting
				if (!submitting) {
					this.submitting = true;
					const data = { ...form,
						...{
							_method: "patch"
						}
					}
					console.log(data)
					// 内容安全审核
					if(!!form.name){
						const checkRes = await wx.serviceMarket.invokeService({
							service: 'wxee446d7507c68b11',
							api: 'msgSecCheck',
							data: {
							  "Action": 'TextApproval',
							  "Text": form.name,
							}
						});
						if(checkRes.data.Response.EvilTokens.length >0 ){
							uni.hideToast();
							uni.showModal({
							    title: '发布失败',
							    content: '您的昵称涉及敏感信息：“'+checkRes.data.Response.EvilTokens[0].EvilKeywords[0]+"”",
							    success: res => {
							        this.submitting = false;
									this.form.name = "";
							    }
							});
							return;
						}
					}else{
						uni.hideToast();
						uni.showModal({
						    title: '发布失败',
						    content: '昵称不允许为空',
						    success: res => {
						        this.submitting = false;
						    }
						});
						return;
					}
					if(!!form.bio){
						const checkResb = await wx.serviceMarket.invokeService({
							service: 'wxee446d7507c68b11',
							api: 'msgSecCheck',
							data: {
							  "Action": 'TextApproval',
							  "Text": form.bio,
							}
						});
						if(checkResb.data.Response.EvilTokens.length >0 ){
							uni.hideToast();
							uni.showModal({
							    title: '发布失败',
							    content: '您的个人介绍涉及敏感信息：“'+checkResb.data.Response.EvilTokens[0].EvilKeywords[0]+"”",
							    success: res => {
							        this.submitting = false;
									this.form.bio = "";
							    }
							});
							return;
						}
					}

					this.$u.api
						.saveUserInfo(data)
						.then((res) => {
							this.submitting = false;
							this.updateUserInfo(data)
							if (res.statusCode == 500) {
								wx.showToast({
									title: '保存失败',
									icon: 'none'
								})
								this.submitting = false
							} else {
								wx.showToast({
									title: '保存成功'
								})
								wx.navigateBack({
									delta: 1
								})
							}

						})
						.catch((res) => {
							wx.showToast({
								title: '保存失败',
								icon: 'none'
							})
							this.submitting = false
						})
				}
			},
		},
	}
</script>

<style lang="scss">
	@import '../var';

	page {
		background-color: #f4f5f5;
	}

	.user-setting {
		.wxCheat {
			margin-top: 20rpx;
		}

		.containerItem {
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-between;
			padding: 0 32rpx;
			background-color: #fff;
			color: #465564;
			font-size: 34rpx;
			border-bottom: 1px solid rgba(235, 235, 235, 1);

			.cityBox {
				padding: 50rpx 10rpx 30rpx 0;

				// width: 85%;
				picker {
					text-align: right;
					line-height: 5rpx;
					padding: 0 0 30rpx 0;

					.picker {
						display: block;
					}
				}
			}

			.birBox {
				padding: 30rpx 20rpx 30rpx 0;

				// width: 85%;
				picker {
					text-align: right;
					line-height: 40rpx;
					padding: 0 0 0rpx 0;

					.picker {
						display: block;
					}
				}
			}

			.imgPos {
				text-align: right;
			}

			.bio {
				width: 70%;
				padding: 40rpx 22rpx 40rpx 0;
				position: relative;

				textarea {
					width: 100%;
				}

				image {
					width: 14rpx;
					height: 24rpx;
				}

				.tip {
					position: absolute;
					right: 0;
					top: 40rpx;
					color: #afb4be;
					font-size: 34rpx;
				}
			}

			.rightContainer {
				padding: 40rpx 0;
				input {
					text-align: right;
					color: #001432;
					font-size: 36rpx;
					line-height: 56rpx;
					padding-right: 20rpx;
					
				}

				textarea {
					text-align: right;
					color: #001432;
					font-size: 30rpx;
					line-height: 30rpx;
				}

				input {
					padding-left: 10rpx;
				}
			}

			.changeBox {
				width: 85%;
				text-align: right;
				padding: 36rpx 22rpx 36rpx 0;
				// border-bottom: 1px solid rgba(235, 235, 235, 1);
			}
		}

		.item {
			display: flex;
			align-items: center;
			padding: 0 22rpx 0 30rpx;
			background-color: $bgcolor-light;

			&>text {
				width: 110rpx;
				color: $info-color;
				line-height: 28rpx;
			}

			&.log {
				padding-right: 0;
			}

			.logs {
				display: flex;
				align-items: center;
				justify-content: space-between;
				width: 100%;
				padding-right: 20rpx;
				border-bottom: 1px solid rgba(235, 235, 235, 1);

				.list {
					display: flex;
					flex: 1;
					flex-wrap: wrap;
					padding: 15rpx 0 20rpx 5rpx;

					.logitem {
						margin: 5rpx 5rpx;
						padding: 12rpx 18rpx;
						color: $text-color;
						font-size: 24rpx;
						background-color: #f4f5f5;
						border-radius: 6rpx;
					}
				}

				image {
					width: 14rpx;
					height: 24rpx;
				}
			}

			&.input {
				align-items: center;
				padding-right: 0;

				&>text {
					width: 110rpx;
					color: $info-color;
					line-height: 28rpx;
				}

				.rightBox {
					width: 100%;
					padding: 36rpx 22rpx 36rpx 0;
					border-bottom: 1px solid rgba(235, 235, 235, 1);

					input,
					textarea {
						color: #001432;
						font-size: 30rpx;
						line-height: 30rpx;
					}

					input {
						padding-left: 10rpx;
					}
				}

				// &.picker {
				//   view {
				//     padding-top: 0;
				//     .picker {
				//       display: block;
				//       padding-left: 10rpx;
				//     }
				//   }
				// }
				&.textarea {
					&.ios {
						text {
							margin-top: 19rpx;
						}
					}

					view {
						padding-top: 0;
						border-bottom: none;
					}

					align-items: flex-start;
					padding-top: 36rpx;
				}
			}

			&.avatar {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding-top: 43rpx;
				padding-bottom: 43rpx;
				border-bottom: 1px solid rgba(235, 235, 235, 1);
				height: 296rpx;

				.image {
					display: flex;
					width: 140rpx;
					height: 140rpx;
					border-radius: 50%;
				}

				.action {
					// display: flex;
					// flex: 1;
					// align-items: center;
					// justify-content: space-between;
					// padding-left: 30rpx;
					// image {
					//   width: 14rpx;
					//   height: 24rpx;
					// }
					margin-top: 34rpx;
					font-size: 28rpx;
					color: #465564;
				}
			}
		}

		.submit {
			margin-top: 50rpx;
			margin-bottom: 50rpx;
			background-color: transparent;

			button {
				display: flex;
				align-items: center;
				justify-content: center;
				color: #fff;
				width: 686rpx;
				height: 88rpx;
				// background: $primary-color;
				background-color: #0046f5;
				border-radius: 343rpx;

				&[disabled]:not([type]) {
					background-color: #e4e5e5;
				}
			}
		}
	}

	.padl10 {
		padding-left: 10rpx !important;
	}

	.img {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 311rpx;
		background-color: #fff;
		border-bottom: 0.5rpx solid $border-color;

		.bg {
			width: 180rpx;
			height: 180rpx;
			border: 1rpx solid $border-color;
			border-radius: 8rpx;

			.cam {
				display: block;
				width: 49rpx;
				height: 43rpx;
				margin: 48rpx auto 20rpx;
			}

			.tips {
				width: 100%;
				height: 24rpx;
				color: #cccccc;
				font-size: 20rpx;
				text-align: center;
			}
		}

		#image-cropper {
			border-radius: 8rpx;
		}
	}

	.magTop20 {
		margin-top: 20rpx;
	}
</style>
